//
//  WDSelectView.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2017/3/2.
//  Copyright © 2017年 王笛. All rights reserved.
//

#import "WDSelectView.h"
#import "WDSelectCell.h"
#import "WDSelectData.h"

@interface WDSelectView ()<UICollectionViewDelegate, UICollectionViewDataSource>
/** 首付比例collectionView */
@property (nonatomic, strong) UICollectionView *payCollectionView;
/** 金额范围collectionView */
@property (nonatomic, strong) UICollectionView *amountCollectionView;
/** 背景 */
@property (nonatomic, strong) UIView *backView;
/** 头部标题 */
@property (nonatomic, strong) UILabel *headLabel;
/** contentView */
@property (nonatomic, strong) UIView *contentView;
/** 金额范围 */
@property (nonatomic, strong) NSArray *amountArr;
/** 保存选中信息的数组 */
@property (nonatomic, strong) NSMutableArray *chooseArr;
@property(nonatomic,assign)CGFloat hightED;

@end

static NSString *cellID = @"selectView";
static NSString *headerViewIdentifier = @"hederview";

@implementation WDSelectView

- (NSArray *)amountArr
{
    if (!_amountArr) {
        _amountArr = @[@"0-10万",
                       @"10–20万", 
                       @"20–50万",
                       @"50万以上"];
    }
    return _amountArr;
}

- (UICollectionView *)creatCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    layout.minimumLineSpacing = 10;
    layout.minimumInteritemSpacing = 0;
    layout.itemSize=CGSizeMake(57, 26);
    layout.headerReferenceSize=CGSizeMake(self.frame.size.width, 50);
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    
    collectionView.backgroundColor = [UIColor whiteColor];
    
    [collectionView registerClass:[WDSelectCell class] forCellWithReuseIdentifier:cellID];
    //注册头视图
    [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewIdentifier];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    [self.contentView addSubview:collectionView];
    
    return collectionView;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        self.chooseArr = [NSMutableArray array];
        
        UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WDScreenW, WDScreenH)];
        self.backView = backView;
        backView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
        
        [self addSubview:backView];
        
        UIView *contentView = [[UIView alloc] init];
        contentView.backgroundColor = [UIColor whiteColor];
        contentView.frame = CGRectMake(WDScreenW, 0, WDScreenW - 80, WDScreenH);
        self.contentView = contentView;
        [self addSubview:contentView];
        
        self.payCollectionView = [self creatCollectionView];
        [self.payCollectionView makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(0);
            make.height.equalTo(100);
        }];
        
        self.amountCollectionView = [self creatCollectionView];
        [self.amountCollectionView makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(0);
            make.bottom.equalTo(44);
            make.top.equalTo(self.payCollectionView.bottom);
        }];
        
        UIButton *cancelBtn = [self creatBtnWithFlag:0];
        cancelBtn.frame = CGRectMake(0, WDScreenH - 48 - 64, (WDScreenW - 80) / 2 , 48);
        [self.contentView addSubview:cancelBtn];
        
        UIButton *sureBtn = [self creatBtnWithFlag:1];
        sureBtn.frame = CGRectMake((WDScreenW - 80) / 2, WDScreenH - 48 - 64, (WDScreenW - 80) / 2 , 48);
        [self.contentView addSubview:sureBtn];
        
        [self showAnimation];
        
    }
    return self;
}

/** flag 0:左 1:右 */
- (UIButton *)creatBtnWithFlag:(BOOL)flag
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [btn setTitleColor:ColorForRGB(0xffffff) forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    
    if (!flag) {
        [btn setTitle:@"取消" forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageWithColor:ColorForRGB(0xa0a0a0)] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageWithColor:ColorForRGB(0x6b6b6b)] forState:UIControlStateHighlighted];
        [btn addTarget:self action:@selector(clickCancel:) forControlEvents:UIControlEventTouchUpInside];
    } else {
        [btn setTitle:@"完成" forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageWithColor:ColorForRGB(0xfd5722)] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageWithColor:ColorForRGB(0xea2221)] forState:UIControlStateHighlighted];
        [btn addTarget:self action:@selector(clickSure:) forControlEvents:UIControlEventTouchUpInside];
    }
    return btn;
}

- (void)clickCancel:(UIButton *)sender
{
    [self hideAniamtion];
}

- (void)clickSure:(UIButton *)sender
{
    if (self.chooseArr.count) {
        //WDLog(@"%@", self.chooseArr);
    }
    
    [_delegate selectArrData:self.chooseArr];
    
    [self hideAniamtion];
}

- (void)showAnimation
{
    [UIView animateWithDuration:0.2 animations:^{
        self.contentView.frame = CGRectMake(80, 0, WDScreenW - 80, WDScreenH - 48);
    }];
}

- (void)hideAniamtion
{
    [UIView animateWithDuration:0.2 animations:^{
        self.contentView.frame = CGRectMake(WDScreenW, 0, WDScreenW - 80, WDScreenH - 48);
    }];
    self.backView.backgroundColor = [UIColor clearColor];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self removeFromSuperview];
    });
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self hideAniamtion];
}

- (void)setDataArr:(NSArray *)dataArr
{
    _dataArr = dataArr;
    
    [self.payCollectionView reloadData];
}

#pragma mark - <UIcollectionView代理>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    if (collectionView == self.payCollectionView) {
        if (self.dataArr.count == 0) {
            
            return 1;
            
        } else {
            
            return self.dataArr.count;
            
        }
    } else {
        return 4;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.payCollectionView) {
        WDSelectCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
        WDSelectData *tempData = self.dataArr[indexPath.row];
        cell.labelStr = tempData.value;
        
        if (self.seleStrArr.count) {
            for (int i = 0; i < self.seleStrArr.count; i++) {
                NSDictionary *tempDict = self.seleStrArr[i];
                if ([cell.labelStr isEqualToString:tempDict[@"chooseStr"]]) {
                    [cell UpdateCellWithState:YES];
                    
                    NSDictionary *chooseDict = @{
                                                 @"chooseStr":cell.labelStr,
                                                 @"indexPath":indexPath
                                                 };
                    
                    [self.chooseArr addObject:chooseDict];
                }
            }
        }
        
        [self updateCollectionViewHight:self.payCollectionView.collectionViewLayout.collectionViewContentSize.height];
        return cell;
        
    } else {
        
        WDSelectCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
        cell.labelStr = self.amountArr[indexPath.row];
        
        if (self.seleStrArr.count) {
            for (int i = 0; i < self.seleStrArr.count; i++) {
                NSDictionary *tempDict = self.seleStrArr[i];
                if ([cell.labelStr isEqualToString:tempDict[@"chooseStr"]]) {
                    
                    [cell UpdateCellWithState:YES];
                    
                    NSDictionary *chooseDict = @{
                                                 @"chooseStr":cell.labelStr,
                                                 @"indexPath":indexPath
                                                 };
                    
                    [self.chooseArr addObject:chooseDict];
                }
            }
        }
        
        return cell;
    }
}

-(void)updateCollectionViewHight:(CGFloat)hight
{
    
    if (self.hightED != hight) {
        
        self.hightED = hight;
        
        [self.payCollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(hight);
        }];
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(20, 20, 20, 20);
}

//  返回头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    //如果是头视图
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *header=[collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerViewIdentifier forIndexPath:indexPath];
        
        if (collectionView == self.payCollectionView)
        {
            //添加头视图的内容
            [self addContentWithIndex:0];
        } else {
            [self addContentWithIndex:1];
        }
        //头视图添加view
        [header addSubview:self.headLabel];
        return header;
    }
    return nil;
}

/*
 *  补充头部内容
 */
-(void)addContentWithIndex:(NSInteger)index
{
    UILabel *headerLabel = [[UILabel alloc] init];
    headerLabel.frame=CGRectMake(20, 20, self.frame.size.width - 80, 20);
    
    headerLabel.textColor = ColorForRGB(0x6b6b6b);
    headerLabel.font = [UIFont systemFontOfSize:16];
    if (index == 0) {
        headerLabel.text = @"首付比例";
    } else {
        headerLabel.text = @"融资金额范围";
    }
    self.headLabel = headerLabel;
    
}

//选中
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_currentSelectIndex!=nil && _currentSelectIndex != indexPath) {
        WDSelectCell * cell = (WDSelectCell *)[collectionView cellForItemAtIndexPath:_currentSelectIndex];
        [cell UpdateCellWithState:NO];
    }
    WDSelectCell * cell = (WDSelectCell *)[collectionView cellForItemAtIndexPath:indexPath];
    [cell UpdateCellWithState:!cell.isSelected];
    _currentSelectIndex = indexPath;
    
    if (cell.isSelected) {
        
        NSDictionary *chooseDict = @{
                                     @"chooseStr":cell.labelStr,
                                     @"indexPath":indexPath
                                     };
        
        [self.chooseArr addObject:chooseDict];
    } else {
        
        NSDictionary *chooseDict = @{
                                     @"chooseStr":cell.labelStr,
                                     @"indexPath":indexPath
                                     };
        
        [self.chooseArr removeObject:chooseDict];
    }
}

//未选中
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
}

//高亮
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    
}

@end
